// 微信认证路由
const express = require("express");
const axios = require("axios");
const wechatConfig = require("../config/wechat");

const router = express.Router();

// 输入验证中间件
const validateCode = (req, res, next) => {
  const { code } = req.query;

  if (!code) {
    return res.status(400).json({
      error: "缺少code参数",
    });
  }

  if (typeof code !== "string" || code.length < 10 || code.length > 200) {
    return res.status(400).json({
      error: "无效的code参数",
    });
  }

  next();
};

const validateTokenParams = (req, res, next) => {
  const { access_token, openid } = req.query;

  if (!access_token || !openid) {
    return res.status(400).json({
      error: "缺少access_token或openid参数",
    });
  }

  if (
    typeof access_token !== "string" ||
    access_token.length < 10 ||
    access_token.length > 512
  ) {
    return res.status(400).json({
      error: "无效的access_token参数",
    });
  }

  if (typeof openid !== "string" || openid.length < 10 || openid.length > 128) {
    return res.status(400).json({
      error: "无效的openid参数",
    });
  }

  next();
};

// 获取openid
router.get("/openid", validateCode, async (req, res) => {
  try {
    const { code } = req.query;
    console.log("收到微信授权code:", code);

    // 使用code换取access_token和openid
    const tokenUrl = wechatConfig.getAccessTokenUrl(code);

    const tokenResponse = await axios.get(tokenUrl, {
      timeout: wechatConfig.getConfig().timeout,
    });

    const tokenData = tokenResponse.data;
    console.log("微信API返回:", tokenData);

    // 检查是否获取成功
    if (tokenData.errcode) {
      const errorMessage =
        wechatConfig.getErrorMessage(tokenData.errcode) || tokenData.errmsg;

      return res.status(400).json({
        error: `微信API错误: ${errorMessage}`,
        errcode: tokenData.errcode,
      });
    }

    const { openid, access_token } = tokenData;

    // 验证获取到的openid
    if (!openid || typeof openid !== "string" || openid.length < 10) {
      return res.status(500).json({
        error: "获取openid失败：返回数据异常",
      });
    }

    // 返回openid给前端
    res.json({
      openid: openid,
      access_token: access_token,
      message: "获取openid成功",
    });
  } catch (error) {
    console.error("获取openid失败:", error);

    // 根据不同类型的错误返回不同的响应
    if (error.code === "ECONNABORTED" || error.code === "ETIMEDOUT") {
      return res.status(504).json({
        error: "微信API调用超时",
      });
    }

    if (error.response) {
      // 微信API返回错误
      return res.status(502).json({
        error: "微信API服务异常",
      });
    }

    res.status(500).json({
      error: "获取openid失败",
      details:
        process.env.NODE_ENV === "production" ? undefined : error.message,
    });
  }
});

// 获取用户基本信息
router.get("/userinfo", validateTokenParams, async (req, res) => {
  try {
    const { access_token, openid } = req.query;

    // 获取用户基本信息
    const userInfoUrl = wechatConfig.getUserInfoUrl(access_token, openid);

    const userInfoResponse = await axios.get(userInfoUrl, {
      timeout: wechatConfig.getConfig().timeout,
    });

    const userInfo = userInfoResponse.data;
    console.log("用户信息:", userInfo);

    if (userInfo.errcode) {
      const errorMessage =
        wechatConfig.getErrorMessage(userInfo.errcode) || userInfo.errmsg;

      return res.status(400).json({
        error: `获取用户信息失败: ${errorMessage}`,
        errcode: userInfo.errcode,
      });
    }

    // 验证返回的用户信息
    if (!userInfo || typeof userInfo !== "object") {
      return res.status(500).json({
        error: "获取用户信息失败：返回数据异常",
      });
    }

    res.json({
      userInfo: userInfo,
      message: "获取用户信息成功",
    });
  } catch (error) {
    console.error("获取用户信息失败:", error);

    // 根据不同类型的错误返回不同的响应
    if (error.code === "ECONNABORTED" || error.code === "ETIMEDOUT") {
      return res.status(504).json({
        error: "微信API调用超时",
      });
    }

    if (error.response) {
      // 微信API返回错误
      return res.status(502).json({
        error: "微信API服务异常",
      });
    }

    res.status(500).json({
      error: "获取用户信息失败",
      details:
        process.env.NODE_ENV === "production" ? undefined : error.message,
    });
  }
});

// 验证access_token是否有效
router.get("/check-token", validateTokenParams, async (req, res) => {
  try {
    const { access_token, openid } = req.query;

    const checkUrl = wechatConfig.getCheckTokenUrl(access_token, openid);

    const checkResponse = await axios.get(checkUrl, {
      timeout: wechatConfig.getConfig().timeout,
    });

    const checkResult = checkResponse.data;

    // 检查返回结果
    if (typeof checkResult !== "object") {
      return res.status(500).json({
        error: "验证token失败：返回数据异常",
      });
    }

    res.json({
      isValid: checkResult.errcode === 0,
      message: checkResult.errmsg || "token有效",
      errcode: checkResult.errcode,
    });
  } catch (error) {
    console.error("验证token失败:", error);

    // 根据不同类型的错误返回不同的响应
    if (error.code === "ECONNABORTED" || error.code === "ETIMEDOUT") {
      return res.status(504).json({
        error: "微信API调用超时",
      });
    }

    if (error.response) {
      // 微信API返回错误
      return res.status(502).json({
        error: "微信API服务异常",
      });
    }

    res.status(500).json({
      error: "验证token失败",
      details:
        process.env.NODE_ENV === "production" ? undefined : error.message,
    });
  }
});

module.exports = router;
